<template>
	<view class="login-container">
		<uni-card title="欢迎登录">
			<view class="input-group">
				<uni-easyinput v-model="loginForm.username" placeholder="请输入用户名" :clearable="true" />
			</view>

			<view class="input-group">
				<uni-easyinput v-model="loginForm.password" type="password" placeholder="请输入密码" :clearable="true" />
			</view>

			<view class="btn-group">
				<button type="primary" @click="handleLogin">登录</button>
				<button @click="handleRegister">注册</button>
			</view>
		</uni-card>
	</view>
</template>

<script>
	import request from '@/utils/request.js'

	export default {
		data() {
			return {
				loginForm: {
					username: '',
					password: ''
				}
			}
		},
		methods: {
			async handleLogin() {
				try {
					const res = await request({
						url: '/auth/login',
						method: 'POST',
						data: this.loginForm
					})

					if (res.data.status === 'success') {
						// Store token and user info
						uni.setStorageSync('token', res.data.data.token)
						uni.setStorageSync('userInfo', res.data.data.user)

						// 根据用户角色设置 tabBar
						if (res.data.data.user.is_admin) {
							uni.setTabBarItem({
								index: 1,
								visible: true
							})
						} else {
							uni.setTabBarItem({
								index: 1,
								visible: false
							})
						}

						// 显示登录成功提示
						uni.showToast({
							title: '登录成功'
						})
						
						// 延迟跳转
						setTimeout(() => {
							if (res.data.data.user.is_admin) {
								uni.switchTab({
									url: '/pages/admin/index'
								})
							} else {
								uni.switchTab({
									url: '/pages/home/index'
								})
							}
						}, 1500)
					}
				} catch (e) {
					uni.showToast({
						title: '登录失败',
						icon: 'none'
					})
				}
			},

			

			handleRegister() {
				uni.navigateTo({
					url: '/pages/auth/register'
				})
			},

			// 登录成功后的处理
			async handleLoginSuccess(res) {
				const { token, user } = res.data.data
				
				// 存储登录状态
				uni.setStorageSync('token', token)
				uni.setStorageSync('userInfo', user)
				
				// 根据用户角色设置 tabBar
				if (user.is_admin) {
					uni.setTabBarItem({
						index: 1,
						visible: true
					})
				} else {
					uni.setTabBarItem({
						index: 1,
						visible: false
					})
				}

				// 跳转到首页
				uni.switchTab({
					url: '/pages/home/index'
				})
				
				uni.showToast({
					title: '登录成功'
				})
			}
		}
	}
</script>

<style lang="scss">
	.login-container {
		padding: 30rpx;

		.input-group {
			margin-bottom: 30rpx;
		}

		.btn-group {
			margin-top: 50rpx;

			button {
				margin-bottom: 20rpx;
			}
		}
	}
</style>